package com.dogdog.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dogdog.UI.DialogOpenFace;
import com.dogdog.UI.PetListView;
import com.dogdog.UI.RoundedImageView;
import com.dogdog.UI.PetinfoAdapter;
import com.dogdog.activity.R;
import com.dogdog.bean.Me;
import com.dogdog.bean.Pet;
import com.dogdog.bean.Status;
import com.dogdog.bean.UserInfoDataBean;
import com.dogdog.manager.C;
import com.dogdog.manager.MyApplication;
import com.dogdog.util.ToastTool;
import com.google.gson.Gson;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class Hand_userInfo extends FragmentActivity {
    /**
     * 展示用户信息的
     */
    private Me m = MyApplication.getMeData();
    private String sex[] = new String[]{"性别保密", "男", "女"};
    private RoundedImageView user_face;
    private PetListView petListView;
    private List<Pet> pets;
    private PetinfoAdapter petAdapter;
    private Button addPet;
    private Gson gson;

    //设置区域
    //意图返回码  1.摄像头 2.图库 3.裁剪
    private int CAMERA_REQUEST_CODE = 1;
    private int GALLERY_REQUEST_CODE = 2;
    private int CROP_REQUEST_CODE = 3;
    //dialog返回码。表示图片的打开方式
    private final int RECODE_CAMEARA = 0;
    private final int RECODE_GRALLERY = 1;

    //数据区
    private String cacheFaceBase64 = null;//头像缓存的数据流

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.userinfo);
        initView();
        userInfoRequest();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (petAdapter != null) {
            petAdapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        gson = new Gson();
        user_face = (RoundedImageView) findViewById(R.id.userinfo_face);
        user_face.setImageBitmap(m.getFaceBitmap());
        ((TextView) findViewById(R.id.tv_title)).setText("个人信息");
        ((TextView) findViewById(R.id.userinfo_name)).setText(m.getName());
        ((TextView) findViewById(R.id.userinfo_sex)).setText(sex[m.getSex()]);
        ((TextView) findViewById(R.id.userinfo_email)).setText(m.getEmail());
        ((TextView) findViewById(R.id.userinfo_hadpet)).setText("宠物数量：" + m.getHadpet());
        pets = new ArrayList<Pet>();
        petListView = new PetListView(Hand_userInfo.this);
        petListView = (PetListView) findViewById(R.id.userinfo_pet_listview);
        petAdapter = new PetinfoAdapter(Hand_userInfo.this, pets);
        petListView.setAdapter(petAdapter);
        addPet = (Button) findViewById(R.id.addPet);
        addPet.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent addPetIntent = new Intent(Hand_userInfo.this, PetInfoRegister.class);
                startActivity(addPetIntent);
            }
        });
    }

    /**
     * 请求区域
     **/
    public void userInfoRequest() {
        StringRequest userInfo = new StringRequest(
                Method.POST,
                C.URL.UserInfo,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Status s = gson.fromJson(response.toString(), Status.class);
                        if (s.getState() == 1) {
                            UserInfoDataBean data = gson.fromJson(response.toString(), UserInfoDataBean.class);
                            petAdapter.setPetData(data.getPetData());
                            petAdapter.notifyDataSetChanged();
                        } else {
                            ToastTool.status(Hand_userInfo.this, s);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ToastTool.show(Hand_userInfo.this, "请求失败");
                    }
                });
        MyApplication.getHttpQueue().add(userInfo);
    }

    public void uploadFaceRequest(final Bitmap bit) {
        StringRequest face = new StringRequest(
                Method.POST,
                C.URL.UploadsFace,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Status s = gson.fromJson(response, Status.class);
                        if (s.getState() == 1) {
                            user_face.setImageBitmap(bit);
                            ToastTool.show(Hand_userInfo.this, "头像更新成功");
                        } else {
                            ToastTool.status(Hand_userInfo.this, s);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ToastTool.show(Hand_userInfo.this, "头像更新失败！");
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> param = new HashMap<String, String>();
                param.put("uid", String.valueOf(MyApplication.getMeData().getID()));
                param.put("img", cacheFaceBase64);
                return param;
            }
        };
        MyApplication.getHttpQueue().add(face);
    }

    //打开头像，选择 本地图库或者摄像头
    public void uploadFace(View v) {
        DialogOpenFace dialog = new DialogOpenFace(this, new DialogOpenFace.OnCustomDialogListener() {
            @Override
            public void back(int code) {
                Intent intent;
                switch (code) {
                    case RECODE_CAMEARA:
                        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, CAMERA_REQUEST_CODE);
                        break;

                    case RECODE_GRALLERY:
                        intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("image/*");
                        startActivityForResult(intent, GALLERY_REQUEST_CODE);
                        break;

                    default:
                        break;
                }
            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (data == null) {
                return;
            } else {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bm = extras.getParcelable("data");
                    Uri uri = saveBitmap(bm);
                    startImageZoom(uri);
                }
            }
        } else if (requestCode == GALLERY_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Uri uri;
            uri = data.getData();
            Uri fileUri = convertUri(uri);
            startImageZoom(fileUri);
        } else if (requestCode == CROP_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Bundle extras = data.getExtras();
            if (extras == null) {
                return;
            }
            Bitmap bit = extras.getParcelable("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bit.compress(Bitmap.CompressFormat.PNG, 60, stream);
            byte[] bytes = stream.toByteArray();
            cacheFaceBase64 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
            uploadFaceRequest(bit);
        }
    }

    //保存选中后的图片缓存在本地
    private Uri saveBitmap(Bitmap bm) {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/com.dogdog.activity");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        File img = new File(tmpDir.getAbsolutePath() + "avater.png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //发送裁剪意图
    private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 180);
        intent.putExtra("outputY", 180);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    private Uri convertUri(Uri uri) {
        InputStream is = null;
        try {
            is = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
